package com.chzu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.chzu.pojo.DataSource;
import com.chzu.service.IDataSourceService;
import com.chzu.service.impl.DataSourceServiceImpl;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liangzhuo
 * @create 2021-10-21-21:42
 */
public class JdbcUtils {

    @Resource
    private static IDataSourceService dataSourceService;

    public static JdbcUtils jdbcUtils;

    /**
     * 将dataSourceService接口加载到该类
     */
    @PostConstruct
    public void init() {
        jdbcUtils = this;
        jdbcUtils.dataSourceService = this.dataSourceService;
    }

    /**
     * 初始化数据源
     *
     * @param dataSourceList 数据源配置信息list
     */
    public static List<String> initCache(List<DataSource> dataSourceList) {
        System.out.println("------初始化多数据源开始------");
        ThreadLocal<List<String>> result = new ThreadLocal<>();
        List<String> list = new ArrayList<>();
        result.set(list);
        //遍历dataSourceList数据
        dataSourceList.forEach(dataSource -> {
            DruidDataSource druidDataSource = new DruidDataSource();
            Connection connection = null;
            try {
                druidDataSource.setUrl(dataSource.getUrl());
                druidDataSource.setDriverClassName(dataSource.getDriverClass());
                druidDataSource.setUsername(dataSource.getUserName());
                druidDataSource.setPassword(dataSource.getPassword());
                druidDataSource.setValidationQuery("select count(*) from dual");
                /*设置最大等待时间*/
                druidDataSource.setMaxWait(10000);
                /*初始化连接数量*/
                druidDataSource.setInitialSize(10);
                /*最大并发连接数*/
                druidDataSource.setMaxActive(25);
                /*超过时间限制是否回收*/
                druidDataSource.setRemoveAbandoned(true);
                /* 超时时间；单位为秒。3600秒=一个小时 */
                druidDataSource.setRemoveAbandonedTimeout(36000);
                /*配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒*/
                druidDataSource.setTimeBetweenConnectErrorMillis(600000);
                /* 关闭abanded连接时输出错误日志 */
                druidDataSource.setLogAbandoned(true);
                connection = druidDataSource.getConnection();
                if (connection != null) {
                    if (dataSource.getType() == 1) {
                        GlobalCache.localDao = new NutDao(druidDataSource);
                    }else{
                        //定义一个Dao 初始化Dao
                        NutDao serverDao = new NutDao(druidDataSource);
                        //将链接数据库的dao  添加到全局静态变量中
                        GlobalCache.dataSourceMap.put(String.valueOf(dataSource.getId()), serverDao);
                    }
                    System.out.println("向数据连接池中加入id:" + dataSource.getId() + "=>的数据源");
                    connection.close();
                }
                result.get().add(String.valueOf(dataSource.getId()));
            } catch (SQLException e) {
                clearDatasouceCache(dataSource.getId());
            } catch (NullPointerException e) {
                druidDataSource.close();
                clearDatasouceCache(dataSource.getId());
            } catch (Exception e) {
                clearDatasouceCache(dataSource.getId());
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("------初始化多数据源结束------");
        return result.get();
    }

    /**
     * 测试数据源连接
     *
     * @param url      url
     * @param driver   driverClassName
     * @param username username
     * @param password password
     * @return 0为失败 1为成功
     */
    public static int testConnect(String url, String driver, String username, String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        int result = 0;
        Connection connection = null;
        try {
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            druidDataSource.setDriverClassName(driver);
//            druidDataSource.setValidationQuery("select count(*) from dual");
            /*设置最大等待时间*/
            druidDataSource.setMaxWait(10000);
            /*初始化连接数量*/
            druidDataSource.setInitialSize(10);
            /*最大并发连接数*/
            druidDataSource.setMaxActive(25);
            /*超过时间限制是否回收*/
            druidDataSource.setRemoveAbandoned(true);
            /* 超时时间；单位为秒。3600秒=一个小时 */
            druidDataSource.setRemoveAbandonedTimeout(36000);
            /*配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒*/
            druidDataSource.setTimeBetweenConnectErrorMillis(600000);
            /* 关闭abanded连接时输出错误日志 */
            druidDataSource.setLogAbandoned(true);
            connection = druidDataSource.getConnection();
            if (connection != null) {
                connection.close();
            }
            result = 1;
        } catch (SQLException e) {
            result = 0;
        } catch (NullPointerException e) {
            result = 0;
            druidDataSource.close();
        } catch (Exception e) {
            result = 0;
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                    druidDataSource.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 清除数据源缓存
     *
     * @param datasourceId
     */
    private static void clearDatasouceCache(Long datasourceId) {
        DataSource dataSourcePojo = new DataSource();
        dataSourcePojo.setId(datasourceId);
        dataSourcePojo.setIsActive(0);
//        datasourceCacheUtils.jkglDataSourceService.updateIscacheJkglDataSourceById(jkglDataSourceCondition);
    }

}
